// 获取全局App实例
const app = getApp();
const { request } = require('../../utils/request.js');
const api = require('../../utils/api.js');
Page({
  data: {
    loading: false,
    remainTimes: 0,
    plans: [],
    selectedPlan: {},
    selectedIndex: 0, // 👈 添加这行
    countdownEl: 0,
  },

  onLoad: function () {
    // return
    // 页面加载时获取用户信息
    this.getPlans()
    this.fetchUnreadCount();


    // // 设置初始倒计时总时间（单位：毫秒）= 30分钟
    // const totalTime = 30 * 60 * 1000;
    // const endTime = Date.now() + totalTime;

    // const timer = setInterval(() => {
    //   const now = Date.now();
    //   let diff = endTime - now;

    //   if (diff <= 0) {
    //     clearInterval(timer);
    //     this.setData({
    //       countdownEl:"00:00:000"
    //     })
    //     return;
    //   }

    //   const minutes = String(Math.floor(diff / (60 * 1000))).padStart(2, "0");
    //   const seconds = String(Math.floor((diff % (60 * 1000)) / 1000)).padStart(2, "0");
    //   const milliseconds = String(diff % 1000).padStart(3, "0");
    //   this.setData({
    //     countdownEl:`${minutes}:${seconds}:${milliseconds}`
    //   })
    // }, 10); // 每10毫秒更新一次（更精确）
  },

  onShow() {

  },
  /**
   * 获取商品列表
   */
  getPlans() {
    const token = wx.getStorageSync('token');
    request(api.plans, 'GET')
      .then(res => {
        const plans = res.data.list.map((item, index) => {
          return {
            ...item,
            highlight: index === 0
          }
        })
        if (res.code === 1 && res.data.list) {
          this.setData({
            plans,
            selectedPlan: plans[0]
          })
        }
      });
  },
  // 检查用户是否已登录
  checkUserLogin: function () {
    const token = wx.getStorageSync('token');
    const userId = wx.getStorageSync('userId');
  },

  selectedPlan(raw) {
    const that = this;
    const idx = raw.currentTarget.dataset.id;
    const selectedPlan = that.data.plans[idx];
    that.setData({
      selectedPlan,
      selectedIndex: idx
    });
  },

  // 购买次数/会员
  buy: function () {
    const that = this;
    const selectedPlan = that.data.selectedPlan;

    // 检查是否已登录
    const userId = wx.getStorageSync('userId');
    const token = wx.getStorageSync('token');

    if (!userId || !token) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    this.setData({
      loading: true
    });


    request(api.createOrder, 'POST', {
      user_id: userId,
      plan_id: selectedPlan.id,
      platform: 'MP'
    })
      .then(res => {
        console.log(res);
        if (res.code === 1 && res.data.payment_params) {
          console.log('订单创建成功', res.data);
          // 发起支付
          that.requestPayment(res.data.payment_params, res.data.order_id);
        } else {
          that.setData({
            loading: false
          });
          wx.showToast({
            title: res.data.msg || '创建订单失败',
            icon: 'none'
          });
        }
      })
      .catch(err => {
        console.error('获取失败', err);
      });
  },

  // 发起微信支付
  requestPayment: function (payParams, orderId) {
    const that = this;

    // 确保timeStamp是字符串类型
    if (typeof payParams.timeStamp !== 'string') {
      payParams.timeStamp = String(payParams.timeStamp);
    }

    wx.requestPayment({
      timeStamp: payParams.timeStamp,
      nonceStr: payParams.nonceStr,
      package: payParams.package,
      signType: payParams.signType,
      paySign: payParams.paySign,
      success(res) {
        that.setData({
          loading: false
        });

        // 更新剩余次数
        that.fetchUnreadCount();

        wx.showToast({
          title: '支付成功',
          icon: 'success'
        });
      },
      fail(err) {
        that.setData({
          loading: false
        });
        console.error('支付失败', err);

        // 用户取消支付
        if (err.errMsg === 'requestPayment:fail cancel') {
          wx.showToast({
            title: '支付已取消',
            icon: 'none'
          });
          return;
        }

        // 其他支付错误
        wx.showToast({
          title: '支付失败: ' + err.errMsg,
          icon: 'none'
        });

      },
      complete() {
        // 支付完成后，无论成功失败，都可以在这里执行操作
      }
    });
  },

  // 查询订单状态
  queryOrderStatus: function (orderId) {
    const token = wx.getStorageSync('token');

    request(api.queryOrderStatus, 'POST', {
      order_id: orderId
    })
      .then(res => {
        if (res.data.is_paid) {
          wx.showToast({
            title: '支付已完成',
            icon: 'success'
          });
        }
      })
      .catch(err => {
        console.error('获取失败', err);
      });
  },

  // 获取剩余使用次数
  fetchUnreadCount: function () {
    request(api.userUsageCount + '?user_id=' + wx.getStorageSync('userId'), 'GET')
      .then(res => {
        this.setData({
          remainTimes: res.data.usage_count
        });
      })
      .catch(err => {
        console.error('获取usage_count失败', err);
      });
  },

  // 跳转到搜题页面
  goMiniProgram() {
    wx.switchTab({
      url: '/pages/photo/photo',
    });
  },

  // 显示购买须知
  showPurchaseInfo: function () {
    wx.showModal({
      title: '购买须知',
      content: '1. 购买的次数无时间限制，永久有效\n2. 包年会员为购买之日起365天内有效\n3. 终身会员永久有效\n4. 付款成功后立即生效\n5. 如有疑问请联系客服',
      showCancel: false
    });
  }
})